<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查看比对任务</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='layui/css/layui.css') }}">

  <style>
    .check-ok {
      background-color: green;
      color: white;
      padding: 5px;
    }

    .check-not-ok {
      background-color: red;
      color: white;
      padding: 5px;
    }

  </style>

</head>
<body>

<form class="layui-form layui-row layui-col-space16" >
  <div class="layui-col-md2">
    <div class="layui-input-wrap">
      <div class="layui-input-prefix">
        <i class="layui-icon layui-icon-tabs"></i>
      </div>
      <input type="text" id="table_name" name="table_name" value="{{ table_name }}" placeholder="表名" class="layui-input" lay-affix="clear">
    </div>
  </div>
  <div class="layui-col-md2">
    <div class="layui-input-wrap">
      <div class="layui-input-prefix">
        <i class="layui-icon layui-icon-cols"></i>
      </div>
      <input type="text" id="column_name" name="column_name" value="{{ column_name }}" placeholder="字段名" lay-affix="clear" class="layui-input">
      <input type="text" hidden name="id" value="{{ id }}">

    </div>
  </div>

  <div class="layui-col-md1">
    <label class="layui-form-label">整体结果:</label>
  </div>
  <div class="layui-col-md1">
    <select id="check_result" name="check_result">
      <option value="" selected>ALL</option>
      <option value="×">×</option>
      <option value="√">√</option>
    </select>
  </div>

  <div class="layui-col-md3">
    <div class="layui-btn-container layui-col-xs12">
      <button  class="layui-btn" lay-submit lay-filter="demo-table-search">
        <i class="layui-icon layui-icon-search"></i>查询
      </button>
      <button  type="reset" class="layui-btn layui-btn-primary">
        <i class="layui-icon layui-icon-set-sm"></i>重置
      </button>

    </div>
  </div>
</form>

<table class="layui-hide" lay-data="{page: true, limit: 6, limits:[6]}" id="ID-table-detailCompareTask"></table>

<script type="text/html" id="toolbarDemo"></script>

<div id="dataid" d="{{data}}" style="display:none"></div>
<div id="source_column_info" d="{{source_column_info}}" style="display:none"></div>
<div id="id" d="{{id}}" style="display:none"></div>
<div id="task_name" d="{{task_name[0]['task_name']}}" style="display:none"></div>

</body>
<script src="{{ url_for('static', filename='js/jquery-3.6.0.min.js') }}"></script>
<script src="{{ url_for('static', filename='layui/layui.js') }}"></script>

<script>

  var table_name_tmp = getUrlParam("table_name");
  var column_name_tmp = getUrlParam("column_name");
  // console.log("getUrlParams(\"table_name\") = " + table_name_tmp);
  document.getElementById("table_name").value = table_name_tmp;
  document.getElementById("column_name").value = column_name_tmp;

  var id_tmp = document.getElementById('id').getAttribute('d');
  // console.log("id_tmp=" + id_tmp);

  var check_result_tmp = getUrlParam("check_result");
  document.getElementById("check_result").value = check_result_tmp

  var task_name_tmp = document.getElementById('task_name').getAttribute('d');
  // console.log("task_name_tmp=" + task_name_tmp);

layui.use(function(){
  var $ = layui.$;
  var table = layui.table;
  var layer = layui.layer;
  var form = layui.form;

  // js获取后端传到前端的对象的值
  var js_data = document.getElementById('dataid').getAttribute('d');
  // console.log(js_data);

  // 单引号替换为双引号
  let js_data2 = js_data.replace(/'/g, '"');
  // console.log(js_data2);

  // json字符串转为json对象 JSON.parse(jsonString)
  var dataJsonObject = JSON.parse(js_data2);

  // json转字符串 JSON.stringify(jsonObject)
  // console.log("dataJsonObject[0]=" + JSON.stringify(dataJsonObject[0]));
  // console.log("dataJsonObject[1]=" + JSON.stringify(dataJsonObject[1]));

<!--  var data = [-->
<!--    JSON.parse(js_data)-->
<!--  ]-->
<!--  alert(data)-->

  // 提取列字段
<!--  var cols1 = [];-->
<!--  for (var field in dataJsonObject[0]) {-->
<!--    if (field != 'id') { // 假设我们不需要显示'id'字段-->
<!--      cols1.push({-->
<!--        field: field,-->
<!--        title: field-->
<!--      });-->
<!--    }-->
<!--  }-->
  // alert(cols)
  // console.log("cols1=" + JSON.stringify(cols1));

  // js获取后端传到前端的对象的值
  var source_column_info_data = document.getElementById('source_column_info').getAttribute('d');
  // console.log("source_column_info_data=" + source_column_info_data);
  source_column_info_data = source_column_info_data.replace(/'/g, '"');
  // console.log("source_column_info_data=" + source_column_info_data);
  source_column_info_data = JSON.parse(source_column_info_data);
  // console.log("source_column_info_data=" + JSON.stringify(source_column_info_data));
  // console.log("source_column_info_data.len=" + JSON.stringify(source_column_info_data.len));
  // console.log("source_column_info_data['len']=" + JSON.stringify(source_column_info_data['len']));
  // console.log("source_column_info_data[0]['len']=" + source_column_info_data[0]['len']);
  column_length = source_column_info_data[0]['len']
  // console.log("source_column_info_data[0]['arr']=" + source_column_info_data[0]['arr']);
  column_names = source_column_info_data[0]['arr']

  var cols2 = [];
  cols2.push({field: 'column_name_check_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {

    // console.log("column_names["+ column_names_item +"]=" + column_names[column_names_item])
    field_name = "s" + (Number(column_names_item) + 1)
    // console.log("field_name=" + field_name)
    // console.log("dataJsonObject[" + column_names_item + "]['" + field_name + "']=" + dataJsonObject[column_names_item][field_name])
    dd = dataJsonObject[column_names_item][field_name]
    // cols2.push({field: field_name, title: column_names[column_names_item], width:120, align: 'center', templet: setSheetCellColor(dd) })
    cols2.push({field: field_name, title: column_names[column_names_item], width:130, align: 'center'})
<!--    cols2.push(-->
<!--    {field: column_names[column_names_item], title: column_names[column_names_item], width:80, align: 'center', templet: function(d){-->
<!--          if(d.column_names[column_names_item] === '√'){-->
<!--            // return '<span style="color: blue">√</span>';-->
<!--            return '<div style="background-color: green; color: white; padding: 5px;">'-->
<!--                   + '√' + '</div>';-->
<!--          } else {-->
<!--            return '<div style="background-color: red; color: white; padding: 5px;">'-->
<!--                   + '×' + '</div>';-->
<!--          }-->
<!--        }});-->


<!--    if (field != 'id') { // 假设我们不需要显示'id'字段-->
<!--      cols1.push({-->
<!--        field: field,-->
<!--        title: field-->
<!--      });-->
<!--    }-->
  }

  cols2.push({field: 'data_type_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "data_type" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:135, align: 'left'})
  }

  cols2.push({field: 'nullable_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "nullable" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:135, align: 'center'})
  }

  cols2.push({field: 'pkey_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "pkey" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:135, align: 'center'})
  }

  cols2.push({field: 'data_default_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "data_default" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:145, align: 'left'})
  }

  cols2.push({field: 'table_comment_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "table_comment" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:135, align: 'left'})
  }

  cols2.push({field: 'column_comment_result', title: '单项', width:80, align: 'center'})
  for (var column_names_item in column_names) {
    field_name = "column_comment" + (Number(column_names_item) + 1)
    cols2.push({field: field_name, title: column_names[column_names_item], width:135, align: 'left'})
  }

  var cols = [];
  cols.push({field: 'table_name', title: '表名', width: 250, align: 'left', fixed: 'left', rowspan : 2});
  cols.push({field: 'column_name', title: '字段名', width:250, align: 'left', fixed: 'left', rowspan : 2});
  cols.push({field: 'total_check_result', title: '汇总', width:80, align: 'center', fixed: 'left', rowspan : 2});
  cols.push({title: '字段是否存在', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '数据类型', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '非空约束', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '主键', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '默认值', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '表注释', width:160, align: 'center', colspan : column_length + 1 });
  cols.push({title: '字段注释', width:160, align: 'center', colspan : column_length + 1 });

  // console.log("cols=" + JSON.stringify(cols));

  // 渲染
  table.render({
    elem: '#ID-table-detailCompareTask',
    url: '/detailCompareTaskData?id=' + {{ id }},  // 此处为静态模拟数据，实际使用时需换成真实接口
    // page: true,
    page : {
        //limits :[10,20,50,100]
        //count: data.length             //数据总数
        limit : 10 //每页显示条数
        , limits : [ 10, 20, 50, 100, 1000 ]
        ,curr : 1 //起始页
        , groups : 5 //连续页码个数
        , prev : '上一页' //上一页文本
        , next : '下一页' //下一页文本
        , first : 1 //首页文本
        //, last: 100                     //尾页文本
        , layout : [ 'prev', 'page', 'next',
                'refresh', 'skip', 'count',
                'limit' ]
    },
    height : 750,
    // toolbar : true,
    toolbar: '#toolbarDemo',
    // defaultToolbar: ['filter', 'exports', 'print'],
    defaultToolbar: [
      'filter',
      {
        name: 'exports',
        onClick: function(obj) {
          // 获得数据并清除临时字段
          var data = table.clearCacheKey(obj.data);
          // 当前示例配置项
          var options = obj.config;
          // 弹出面板
          obj.openPanel({
            list: [ // 列表
              '<li data-type="csv">导出 CSV 文件</li>',
              '<li data-type="xls">导出 XLS 文件</li>'
            ].join(''),
            done: function(panel, list) { // 操作列表
              list.on('click', function() {
                var type = $(this).data('type')
                if (type === 'csv') {
                   // 调用内置导出方法
                  // table.exportFile(options.id, jsonObject2, type);

                  $.ajax({
                    type:"get",
                    url: '/detailCompareTaskData?id=' + {{ id }},
                    data: {
                       "limit" : "1000000",
                       "page"  : "1"
                    },
                    dataType:"json",
                    success:function(rd){
                        // console.log("rd=" + JSON.stringify(rd));
                        // console.log("rd['data']=" + rd['data']);
                        // var dataJson = JSON.stringify(rd);
                        // document.write(dataJson);
                        // console.log(dataJson.code);
                        table.exportFile(options.id, rd['data'], type);
                    },
                    error:function(){
                    }
                  });

                } else if(type === 'xls') {
                  $.ajax({
                    type:"get",
                    url: '/detailCompareTaskData?id=' + {{ id }},
                    data: {
                       "limit" : "1000000",
                       "page"  : "1"
                    },
                    dataType:"json",
                    success:function(rd){
                        table.exportFile(options.id, rd['data'], type);
                    },
                    error:function(){
                    }
                  });
                }
              });
            }
          });
        }
      },
      'print'
    ],

    title: getCurrentDateTime() + '-“' + task_name_tmp + '”-表模型比对结果',
    where : {
      "table_name"  : table_name_tmp,
      "column_name" : column_name_tmp,
      "id" : id_tmp,
      "check_result" : check_result_tmp
    },
<!--    css: [ // 设置单元格样式-->
<!--      // 取消默认的溢出隐藏，并设置适当高度-->
<!--      '.layui-table-cell{height: 50px; line-height: 40px;}',-->
<!--      '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',-->
<!--      '.layui-table-cell select{height: 36px; padding: 0 5px;}'-->
<!--    ].join(''),-->
    cols: [cols, cols2],
    loading : true,
    done: function(res, curr, count){
      // console.log("res=" + JSON.stringify(res));
<!--      $('table tbody tr').each(function(){-->
<!--        var $this = $(this);-->
<!--        console.log("$this=" + JSON.stringify($this));-->
<!--        // 获取行数据或其他条件-->
<!--        if(1===1){-->
<!--          $this.find('td').css('background-color', 'yellow');-->
<!--        }-->
<!--      });-->

      // 遍历表格中的每一行
      $('.layui-table tbody tr').each(function(){
        // 获取当前行的所有单元格
        var $cells = $(this).children('td');

        // 遍历每一个单元格
        $cells.each(function(){
          var $cell = $(this);
          var value = $cell.text();

          // 假设我们想为值大于10的单元格设置背景色
          if (value === '√') {
            // $cell.css('background-color', 'green');
            $cell.addClass('check-ok');

          } else if (value === '×') {
            // $cell.css('background-color', 'red');
            $cell.addClass('check-not-ok');
          }
        });
      });

    }
  });

  // 搜索提交
  form.on('submit(demo-table-search)', function(data){
    var field = data.field; // 获得表单字段
    table_name_tmp = field['table_name'];
    column_name_tmp = field['column_name'];
    check_result_tmp = field['check_result'];
    // 执行搜索重载
    table.reload('ID-table-detailCompareTask', {
      page: {
        curr: 1 // 重新从第 1 页开始
      },
      method : 'get',
      // url: '/detailCompareTaskData?id=' + {{ id }},  // 此处为静态模拟数据，实际使用时需换成真实接口
      where : {
        "table_name"  : table_name_tmp,
        "column_name" : column_name_tmp,
        "id" : id_tmp,
        "check_result" : check_result_tmp
      }
    });
    // layer.msg('搜索成功<br>此处为静态模拟数据，实际使用时换成真实接口即可');
    return false; // 阻止默认 form 跳转
  });

  // 导出按钮的点击事件
  $('#exportBtn').on('click', function(){
    exportDataToExcel();
  });

});

function exportDataToExcel() {
  // 获取表格数据
  var tableData = layui.table.cache['#ID-table-detailCompareTask'];

  // 转换数据为SheetJS可识别的格式
  var ws = XLSX.utils.json_to_sheet(tableData);

  // 创建工作簿
  var wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  // 导出为Excel文件
  XLSX.writeFile(wb, 'exportedData.xlsx');
}

//获取地址栏参数，key:参数名称
function getUrlParams(key) {
	let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
	let r = window.location.search.substr(1)
		.match(reg);
	if (r != null)
		return unescape(r[2]);
	return null;
}
//获取地址栏参数//可以是中文参数
function getUrlParam(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

function setSheetCellColor(d){
  if(d === '√'){
    // return '<span style="color: blue">√</span>';
    return '<div style="background-color: green; color: white; padding: 5px;">'
           + '√' + '</div>';
  } else {
    return '<div style="background-color: red; color: white; padding: 5px;">'
           + '×' + '</div>';
  }
}

<!--function getCurrentDateTime() {-->
<!--    const now = new Date();-->
<!--    const year = ('0000' + now.getFullYear()).slice(-4);-->
<!--    const month = ('00' + (now.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要+1-->
<!--    const day = ('00' + now.getDate()).slice(-2);-->
<!--    const hour = ('00' + now.getHours()).slice(-2);-->
<!--    const minute = ('00' + now.getMinutes()).slice(-2);-->
<!--    return `${year}${month}${day}-${hour}${minute}`;-->
<!--}-->

function getCurrentDateTime() {
    const now = new Date();
    const year = ('0000' + now.getFullYear()).slice(-4);
    const month = ('00' + (now.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要+1
    const day = ('00' + now.getDate()).slice(-2);
    const hour = ('00' + now.getHours()).slice(-2);
    const minute = ('00' + now.getMinutes()).slice(-2);
    const second = ('00' + now.getSeconds()).slice(-2);
    return `${year}${month}${day}-${hour}${minute}${second}`;
}

// 调用函数并打印结果
console.log(getCurrentDateTime());
</script>

</html>